﻿using Common.AspNetCore;
using File.Api.Models;
using File.Data.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace File.Api.Repository
{
    public class FileRepository : CoreRepository
    {
        private readonly ICommonModelRepository repository;

        public FileRepository(IServiceProvider provider, ICommonModelRepository repository)
            : base(provider)
        {
            this.repository = repository;
        }

        public async Task<List<t_file>> GetFilesByIdsAsync(List<string> ids)
        {
            var r = await this.Repository.GetEntitiesAsync<t_file>(this.Repository.GetApiParamByIds(ids), ids);
            return r;
        }

        public async Task<FileGroupOrderModel> GetFileGroupOrderByIdsModelAsync(List<string> ids)
        {
            FileGroupOrderModel ret = new FileGroupOrderModel();
            var filegroups = await this.Repository.GetEntitiesAsync<t_file_group>(ids);
            if (filegroups == null || !filegroups.Any())
            {
                return null;
            }

            ret.FileGroups = filegroups; 
            var r1 = await this.Repository.GetEntitiesAsync<t_file_group_detail>(this.Repository.GetApiParamByIds(ids), t => ids.Contains(t.file_group_id));
            ret.FileGroupDetails = r1;
            return ret;
        }

        public async Task SaveFileModelAsync(SaveFileModel model)
        {
            await CommitChangesAsync(() =>
            {
                this.Repository.AddEntities(model.AddFiles);
            });
        }

        public async Task SaveFileGroupModelAsync(SaveFileGroupModel model)
        {
            await CommitChangesAsync(() =>
            {
                this.Repository.AddEntities(model.AddFileGroups);
                this.Repository.AddEntities(model.AddFileGroupDetails);
            });
        }
    }
}
